<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>小方块移动◾</title>
  <style>
    .container {
      width: 500px;
      height: 500px;
      border: 2px solid #000;
      margin: 50px auto;
      position: relative;
    }

    #box {
      width: 100px;
      height: 100px;
      background: #000;
      position: absolute;
      left: 0;
      top: 0;
    }
  </style>
</head>

<body>
  <div class="container">
    <div id="box"></div>
  </div>
  <script>
    const box = document.getElementById('box')
    // 键盘事件要绑定在document身上
    document.addEventListener("keydown", function (e) {
      // 判断摁没摁shift键，来判断小方块移动速度
      console.log(e.shiftKey);
      let speed = e.shiftKey ? 20 : 5;

      if (e.keyCode === 37 && box.offsetLeft > 0) {//⬅️
        box.style.left = box.offsetLeft - speed + 'px';
      } else if (e.keyCode === 38 && box.offsetTop > 0) {//⬆️
        box.style.top = box.offsetTop - speed + 'px';
      } else if (e.keyCode === 39 && box.offsetLeft < 400) {//➡️
        box.style.left = box.offsetLeft + speed + 'px';
      } else if (e.keyCode === 40 && box.offsetTop < 400) { //⬇️
        box.style.top = box.offsetTop + speed + 'px';
      }
    }, false)

  </script>
</body>

</html>